<!--
 * @Author: XieQiu 雪球
 * @Date: 2021-06-03 15:06:59
 * @LastEditTime: 2022-05-14 10:06:53
 * @LastEditors: 血雪球 wash0226@outlook.com
 * @Description: 设备台账信息页面
-->
<template>
  <BaseMainSlot :show-tab="true" :show-search-box="false">
    <template v-slot:btn-box>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-cancel="false"
        :has-save="false"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:tab-select>
      <div class="flex-start">
        <SelectButton @topitemtype="topitemtype" />
        <div class="total">{{ topitemNames }} 总数 {{ totalSize }} 台</div>
      </div>
      <SelectButtons :groupid="groupId" @topitemtypes="topitemtypes" @topitemName="topitemName" />
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="equipmentTypeName" label="所属设备类型" />
        <el-table-column prop="equipmentName" label="设备名称" />
        <el-table-column prop="factoryNumber" label="设备编号">
          <template v-if="scope.row.equipmentName" slot-scope="scope">
            <span v-if="scope.row.factoryNumber">{{ scope.row.factoryNumber }}</span><span v-else>——</span>
          </template>
        </el-table-column>
        <el-table-column prop="worth" label="设备价值">
          <template v-if="scope.row.equipmentName" slot-scope="scope">
            {{ scope.row.worth }} <span v-if="scope.row.worth">元</span><span v-else>——</span>
          </template>
        </el-table-column>
        <el-table-column prop="productionEnterprises" label="生产企业" />
        <el-table-column prop="brand" label="品牌">
          <template v-if="scope.row.equipmentName" slot-scope="scope">
            <span v-if="scope.row.brand">{{ scope.row.brand }}</span><span v-else>——</span>
          </template>
        </el-table-column>
        <el-table-column prop="model" label="型号" />
        <el-table-column width="180" label="操作">
          <template v-if="scope.row.equipmentTypeId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="dbHandleEdit(scope.row)"><i class="el-icon-view"></i> 查看</el-button>
            <el-button class="text-btn-cursor" type="text" size="small" @click="handleEdit(scope.row)"><i class="el-icon-edit-outline"></i> 修改</el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="" label="" /> -->
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <!-- 修改 添加 -->
      <el-dialog
        :title="titleText + equipmentName"
        :visible.sync="dialogFormVisible"
        :before-close="handleClose"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            label="所属设备类型:"
            prop="equipmentTypeId"
            class="w50p"
          >
            <el-select v-model="formData.equipmentTypeId" :disabled="!canInput" filterable clearable @change="equipmentParameter">
              <el-option
                v-for="item in equipmentTypeArr"
                :key="item.equipmentTypeId"
                :label="item.equipmentTypeName"
                :value="item.equipmentTypeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称:" prop="equipmentName" class="w50p">
            <el-input
              v-model="formData.equipmentName"
              placeholder="请输入设备名称"
              :disabled="!canInput"
            />
          </el-form-item>
          <!-- <h4 v-if="paramete">参数:</h4> -->
          <div v-if="paramete" class="parameteClass w100p">
            <el-form-item v-for="item in parameterList" :key="item.equipmentTypeTemplateId" :label="item.paramName + ':'" :prop="item.paramValue" class="w50p">
              <el-input
                v-model="item.fieldValue"
                :placeholder="'请输入' + item.paramName"
                :disabled="!canInput"
                @change="paramValueList($event, item.equipmentTypeTemplateId)"
              />
            </el-form-item>
          </div>
          <el-form-item label="设备编号:" class="w50p">
            <el-input
              v-model="formData.factoryNumber"
              placeholder="请输入设备编号"
              :disabled="!canInput"
            />
          </el-form-item>
          <el-form-item label="生产企业:" class="w50p">
            <el-input
              v-model="formData.productionEnterprises"
              placeholder="请输入生产企业"
              :disabled="!canInput"
            />
          </el-form-item>
          <el-form-item label="品牌:" class="w50p">
            <el-input
              v-model="formData.brand"
              placeholder="请输入品牌"
              :disabled="!canInput"
            />
          </el-form-item>
          <el-form-item label="型号:" class="w50p">
            <el-input
              v-model="formData.model"
              placeholder="请输入型号"
              :disabled="!canInput"
            />
          </el-form-item>
          <el-form-item label="设备价值:" class="w50p">
            <el-input
              v-model="formData.worth"
              placeholder="请输入设备价值"
              :disabled="!canInput"
            >
              <template slot="append">
                元
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注:" prop="description" class="w50p">
            <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入备注(选填)"
              :autosize="{ minRows: 2, maxRows: 4 }"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <!-- 展示 -->
      <el-dialog
        :title="formeData.equipmentName + '信息'"
        :visible.sync="dialogEquipmentVisible"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            label="所属设备类型:"
            prop="equipmentTypeId"
            class="w50p"
          >
            <el-select v-model="formeData.equipmentTypeId" disabled filterable clearable @change="equipmentParameter">
              <el-option
                v-for="item in equipmentTypeArr"
                :key="item.equipmentTypeId"
                :label="item.equipmentTypeName"
                :value="item.equipmentTypeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备名称:" prop="equipmentName" class="w50p">
            <el-input
              v-model="formeData.equipmentName"
              placeholder="请输入设备名称"
              disabled
            />
          </el-form-item>
          <!-- <h4 v-if="paramete">参数:</h4> -->
          <div v-if="formeData.equipmentTypeTemplates" class="parameteClass w100p">
            <el-form-item v-for="item in formeData.equipmentTypeTemplates" :key="item.equipmentTypeTemplateId" :label="item.paramName + ':'" :prop="item.paramValue" class="w50p">
              <el-input
                v-model="item.fieldValue"
                :placeholder="item.fieldValue ? '请输入' + item.paramName : '暂无' + item.paramName"
                disabled
              />
            </el-form-item>
          </div>
          <el-form-item label="设备编号:" class="w50p">
            <el-input
              v-model="formeData.factoryNumber"
              :placeholder="formeData.factoryNumber ? '请输入设备编号' : '暂无数据'"
              disabled
            />
          </el-form-item>
          <el-form-item label="生产企业:" class="w50p">
            <el-input
              v-model="formeData.productionEnterprises"
              :placeholder="formeData.productionEnterprises ? '请输入生产企业' : '暂无生产企业'"
              disabled
            />
          </el-form-item>
          <el-form-item label="品牌:" class="w50p">
            <el-input
              v-model="formeData.brand"
              :placeholder="formeData.brand ? '请输入品牌' : '暂无品牌'"
              disabled
            />
          </el-form-item>
          <el-form-item label="型号:" class="w50p">
            <el-input
              v-model="formeData.model"
              :placeholder="formeData.model ? '请输入型号' : '暂无型号'"
              disabled
            />
          </el-form-item>
          <el-form-item label="设备价值:" class="w50p">
            <el-input
              v-model="formeData.worth"
              :placeholder="formeData.worth ? '请输入设备价值' : '暂无设备价值'"
              disabled
            >
              <template slot="append">
                元
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注:" prop="description" class="w50p">
            <el-input
              v-model="formeData.remark"
              type="textarea"
              :placeholder="formeData.remark ? '请输入备注(选填)' : '暂无备注'"
              :autosize="{ minRows: 2, maxRows: 4 }"
              disabled
              clearable
            />
          </el-form-item>
        </el-form>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import SelectButtons from "../components/selcetButton/selcetButtons.vue";
import SelectButton from "../components/selcetButton/index.vue";
import equipmentTypeManage from "@/api/digital-operation/equip-fac-manage/equip-type-manage";
import EquipmentTemplate from "@/api/basic-info-manage/equipment-template-manage";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixin";
export default {
  name: "",
  components: { Pagination, ActionBar, SelectButtons, SelectButton, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      obj: {
        name: ""
      },
      topitemtypeid: "",
      groupId: 0,
      // 设备类型Id
      equipmentTypeId: "",
      // 设备名称
      equipmentName: '',
      equipmentTypeName: "",
      // 设备 总数
      topitemNames: '',
      // 设备类型数组
      equipmentTypeArr: [],
      // 添加修改
      parameterList: [],
      // 展示
      formeData: {},
      dialogEquipmentVisible: false,
      paramete: null,
      titleText: null,
      rules: {
        equipmentTypeId: [
          { required: true, message: "请选择设备类型", trigger: "change" }
        ],
        equipmentName: [
          { required: true, message: "请输入设备名称", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    formData: {
      async handler(val) {
        if (!val.equipmentTypeId) {
          this.paramete = null
        }
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 获取点击的分页index
    topitemtype(e) {
      this.groupId = e;
      // 获取表格数据
      this.formData = {};
      this.tableData = [];
      this.topitemtypes()
      this.topitemName()
      this.queryEquipmentTypeList();
      if (this.groupId === 1) {
        this.equipmentName = '农机设备信息'
      } else if (this.groupId === 2) {
        this.equipmentName = '加工设备信息'
      }
    },
    // 获取点击的分页index
    topitemtypes(e) {
      this.topitemtypeid = e;
      // 获取表格数据
      this.getTableDataList();
    },
    topitemName(e) {
      this.topitemNames = e;
    },
    async getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        equipmentTypeId: this.topitemtypeid || 0,
        groupId: this.groupId
      };
      const { data: res } = await equipmentTypeManage.getEquipmentList(params);
      this.loading = false;
      let data = res;
      // 赋值总条数
      if (data) {
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.addblankmet();
        this.resetActionBar();
      }
    },
    // 条件查询所有设备类型
    async queryEquipmentTypeList() {
      this.equipmentTypeArr = [];
      let params = {
        organizationNo: sessionStorage.organizationNo,
        groupId: this.groupId
        // equipmentTypeId: this.topitemtypeid
      }
      const { data: res } = await equipmentTypeManage.queryEquipmentTypeList(params);
      this.equipmentTypeArr = res;
    },
    async equipmentParameter(val) {
      if (val) {
        const { data: res } = await EquipmentTemplate.queryIpmentTypeList(val)
        if (res.equipmentTypeTemplates) {
          this.parameterList = JSON.parse(JSON.stringify(res.equipmentTypeTemplates))
          this.paramete = res.equipmentTypeTemplates[0]
          // console.log(this.parameterList)
        }
      } else {
        this.paramete = null
      }
      // console.log(this.parameterList)
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    paramValueList($event, val) {
      // console.log($event, val)
      this.parameterList.forEach(item => {
        if (item.equipmentTypeTemplateId === val) {
          item['fieldValue'] = $event
          // this.parameList.p
          // console.log(item.paramValue)
        }
      })
      // console.log(this.parameterList)
    },
    async handleEdit(row) {
      // TODO 点击行元素后 edit
      if (row.equipmentId) {
        this.formData = JSON.parse(JSON.stringify(row));
        const { data: res } = await equipmentTypeManage.queryEquipment(row.equipmentId)
        if (res) {
          this.parameterList = JSON.parse(JSON.stringify(res.equipmentTypeTemplates))
          this.paramete = res.equipmentTypeTemplates[0]
        }
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
        this.canInput = false;
        this.dialogFormVisible = true;
      }
    },
    async dbHandleEdit(row) {
      if (row.equipmentId) {
        const { data: res } = await equipmentTypeManage.queryEquipment(row.equipmentId)
        this.dialogEquipmentVisible = true
        // this.equipmentName = JSON.parse(JSON.stringify(res.equipmentName))
        this.formeData = JSON.parse(JSON.stringify(res))
        // console.log(res)
      }
    },
    handleSelectionChange(list) {
      this.equipmentIdList = [];
      this.equipmentIdList = list.map(item => item.equipmentId);
      if (this.equipmentIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      equipmentTypeManage.delAllEquipment(this.equipmentIdList).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getTableDataList();
          this.resetActionBar();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      });
    },
    handleMessage(row) {
      equipmentTypeManage.delAllEquipment([row.equipmentId]).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getTableDataList();
          this.resetActionBar();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // this.formData.equipmentTypeId = this.topitemtypeid;
            this.formData.groupId = this.groupId;
            this.formData.equipmentTypeTemplates = this.parameterList
            equipmentTypeManage.editAllEquipment(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.$refs[formData].resetFields()
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            // this.formData.equipmentTypeId = this.topitemtypeid;
            setTimeout(() => {
              this.formData.groupId = this.groupId;
              this.formData.organizationNo = sessionStorage.organizationNo;
              this.formData.equipmentTypeTemplates = this.parameterList
              // console.log(this.formData)
              // this.return
              equipmentTypeManage.addAllEquipment(this.formData).then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg || "新增成功！");
                  this.$refs[formData].resetFields()
                  this.getTableDataList();
                } else {
                  this.$message.error(res.msg || "新增失败！");
                }
              });
            }, 200)
          }
        } else {
          return false;
        }
      });
    },
    handleClose(done) {
      this.cancel('formData')
      done();
      this.resetActionBar();
    //   this.$confirm("确认关闭？")
    //     .then(_ => {
    //     })
    //     .catch(_ => {});
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep .el-form-item__label {
  min-width: 120px !important;
  text-align: end;
}
::v-deep .common-layout {
    margin-top: 15px;
}
.total {
  margin-left: 20px;
}
::v-deep .el-form-item.is-error {
  .el-input__inner {
    border-color: #f56c6c !important;
  }
}

::v-deep .butt-list-sty {
  position:absolute;
  transform: translateY(-150%) !important;
  // z-index: 99;
  width: 30% !important;
  .basebut1 {
  transform: translateY(0%) !important;

  }
  .basebut2 {
    transform: translateY(0%) !important;
  }
}

::v-deep .butt-list-stys {
  position:absolute;
  transform: translateY(-30%) !important;
  z-index: 99;
  .basebut1 {
  transform: translateY(0%) !important;

  }
  .basebut2 {
    transform: translateY(0%) !important;
  }
}
::v-deep .parameteClass {
//  .el-form-item__label {
//   min-width: 120px !important;
//   text-align: end;
//   }
    // border: 1px dashed #d9d9d9;
    // padding: 2px 2px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between
}
::v-deep .el-input-group--append {
  height: 36px;
}
</style>
